package easy;

public class MergeTwoSortedLists {
	public static void main(String[] args) {
		ListNode result = new MergeTwoSortedLists().mergeTwoLists(new ListNode(1), new ListNode(2));
		while(result != null){
			System.out.println(result.val);
			result = result.next;
		}
	}
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
    	ListNode result = null;
    	if(l1 != null && l2 != null){
    		if(l1.val > l2.val){
    			result = new ListNode(l2.val);
    			l2 = l2.next;
    		}else{
    			result = new ListNode(l1.val);
    			l1 = l1.next;
    		}
    	}else if(l1 != null && l2 == null){
    		result = new ListNode(l1.val);
    		l1 = l1.next;
    	}else if(l1 == null && l2 != null){
    		result = new ListNode(l2.val);
    		l2 = l2.next;
    	}
    		
    	
    	ListNode p = result;
    	while(true){
    		if(l1 == null && l2 == null)
    			break;
    		else if(l1 == null && l2 != null)
    		{
    			ListNode temp = new ListNode(l2.val);
    			p.next = temp;
    			l2 = l2.next;
    		}else if(l1 != null && l2 == null){
    			ListNode temp = new ListNode(l1.val);
    			p.next = temp;
    			l1 = l1.next;
    		}else{
    			if(l1.val <= l2.val)
    			{
        			ListNode temp = new ListNode(l1.val);
        			p.next = temp;
    				l1 = l1.next;
    			}else{
        			ListNode temp = new ListNode(l2.val);
        			p.next = temp;
    				l2 = l2.next;
    			}
    				
    		}
    		p = p.next;
    	}
        return result;
    }
}
